var tls = require('tls'),
	sys = require('sys'),
	fs = require('fs');

exports.login = function(port, username, password, callback)
{
	tlsConnection({
    	action: 'login',
    	username : username,
    	password : password,		
    	port : port
    }, callback);
}

exports.register = function(username, password, callback)
{
	tlsConnection({
    	action: 'register',
    	username : username,
    	password : password
    }, callback);
}

exports.upload = function(file, callback)
{
	tlsConnection({
    	action: 'upload',
    	file: file
    });
}

function tlsConnection(data, callback)
{
	var tlsServerAddress = '127.0.0.1',
		tlsServerPort = 8000;

	var options =
	{
	    ca: fs.readFileSync('cert.pem'),
	    host: tlsServerAddress,
	    port: tlsServerPort
	};	

	var client = this;

	client.socket = tls.connect(options, function()
	{
	    if (client.socket.authorized)
	    {
	        sys.puts("Auth success, connected to TLS server");
	    } else {
	        sys.puts("Failed to auth TLS connection: ");
	        sys.puts(client.socket.authorizationError);
	    }

	    client.socket.write(JSON.stringify(data));
	});

	if(callback)
		client.socket.addListener("data", callback);
}